package com.rongke.web.upload;

import com.alibaba.fastjson.JSONObject;
import com.rongke.commons.FailException;
import com.rongke.commons.JsonResp;
import com.rongke.enums.FileType;
import com.rongke.utils.ArrayUtils;
import com.rongke.web.config.Config;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "/api/attachment")
public class FileUploadController {

	private static final Logger LOGGER = Logger
			.getLogger(FileUploadController.class);

	/**
	 * @param files
	 * @param type
	 *            文件类型
	 * @throws Exception
	 *             加密失败
	 */
	@RequestMapping(value = "/singleUpload", method = RequestMethod.POST)
	public JsonResp uploadSingleFile(
			@RequestParam(value = "file", required = false) MultipartFile file,
			FileType fileType) throws Exception {
		try {
			if (null == file || null == fileType) {
				return JsonResp.fa(null);
			}

			// 文件存储目录
			String filePath = fileType.getAbsolutePath();
			File rootFolder = new File(filePath);
			if (!rootFolder.exists()) {
				rootFolder.mkdirs();
			}

			String realFileName = UUID.randomUUID().toString()
					.replaceAll("-", "");
			String originalFileName = file.getOriginalFilename();
			int index = originalFileName.lastIndexOf('.');
			if (index >= 0) {
				realFileName += originalFileName.substring(index);
			}
			File saveFile = new File(filePath + File.separator + realFileName);
			file.transferTo(saveFile);
			String fileUrl = fileType.getFileUrl() + "/" + realFileName;

			JSONObject jsonObj = new JSONObject();
			jsonObj.put("fileUrl", fileUrl);
			return JsonResp.ok(jsonObj);
		} catch (Exception e) {
			LOGGER.error("uploadSingleFile failed", e);
			return JsonResp.fa(null);

		}
	}

	/**
	 * @param files
	 *            多文件
	 * @param type
	 *            文件类型
	 * @throws Exception
	 *             加密失败
	 */
	@RequestMapping(value = "/batchUpload", method = RequestMethod.POST)
	public JsonResp batchUpload(
			@RequestParam(value = "file", required = false) MultipartFile[] files,
			FileType fileType) throws Exception {
		if (ArrayUtils.isEmpty(files) || null == fileType) {
			LOGGER.error("batchUpload input empty");
			return JsonResp.fa(null);
		}
		try {
			// 文件存储目录
			String filePath = fileType.getAbsolutePath();
			File rootFolder = new File(filePath);
			if (!rootFolder.exists()) {
				rootFolder.mkdirs();
			}

			List<String> fileUrlList = new ArrayList<String>();
			for (MultipartFile file : files) {
				if (null == file) {
					continue;
				}

				String realFileName = UUID.randomUUID().toString()
						.replaceAll("-", "");
				String originalFileName = file.getOriginalFilename();
				int index = originalFileName.lastIndexOf('.');
				if (index >= 0) {
					realFileName += originalFileName.substring(index);
				}
				File saveFile = new File(filePath + File.separator
						+ realFileName);
				file.transferTo(saveFile);
				String fileUrl = fileType.getFileUrl() + "/" + realFileName;
				fileUrlList.add(fileUrl);
			}
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("fileUrlList", fileUrlList);

			return JsonResp.ok(jsonObj);
		} catch (Exception e) {
			LOGGER.error("uploadSingleFile failed", e);
			return JsonResp.fa(null);

		}
	}

	/**
	 * @param files
	 *            多文件
	 * @param type
	 *            文件类型
	 * @throws Exception
	 *             加密失败
	 */
	@RequestMapping(value = "/batchUploadList", method = RequestMethod.POST)
	public JsonResp batchUploadList(
			@RequestParam(value = "file", required = false) List<MultipartFile> files,
			FileType fileType) throws Exception {
		if (CollectionUtils.isEmpty(files) || null == fileType) {
			LOGGER.error("batchUpload input empty");
			return JsonResp.fa(null);
		}
		try {
			// 文件存储目录
			String filePath = fileType.getAbsolutePath();
			File rootFolder = new File(filePath);
			if (!rootFolder.exists()) {
				rootFolder.mkdirs();
			}

			List<String> fileUrlList = new ArrayList<String>();
			for (MultipartFile file : files) {
				if (null == file) {
					continue;
				}

				String realFileName = UUID.randomUUID().toString()
						.replaceAll("-", "");
				String originalFileName = file.getOriginalFilename();
				int index = originalFileName.lastIndexOf('.');
				if (index >= 0) {
					realFileName += originalFileName.substring(index);
				}
				File saveFile = new File(filePath + File.separator
						+ realFileName);
				file.transferTo(saveFile);
				String fileUrl = fileType.getFileUrl() + "/" + realFileName;
				fileUrlList.add(fileUrl);
			}
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("fileUrlList", fileUrlList);

			return JsonResp.ok(jsonObj);
		} catch (Exception e) {
			LOGGER.error("uploadSingleFile failed", e);
			return JsonResp.fa(null);

		}
	}
	//
	// /**
	// * @param files
	// * 多文件
	// * @param type
	// * 文件类型
	// * @throws Exception
	// * 加密失败
	// */
	// @RequestMapping(method = RequestMethod.POST)
	// public JsonResp<String[]> batch2(File[] files, FileType type,
	// HttpServletRequest request) throws Exception {
	// if (ArrayUtils.isEmpty(files)) {
	// throw new FailException("文件至少要有一个");
	// }
	// String[] paths = FileType.getPath(type, files.length, request);
	// String[] urls = new String[files.length];
	// for (int i = 0; i < paths.length; i++) {
	// String path = paths[i];
	// File file = files[i];
	// // 获取文件的后缀
	// String suffix;
	// try {
	// suffix = file.getName().substring(
	// file.getName().lastIndexOf("."));
	// } catch (Exception e) {
	// suffix = "";
	// }
	//
	// String fileName = UUID.randomUUID().toString();
	// fileName += suffix;
	// File saveFile = new File(path + File.separator + fileName);
	// FileUtils.copyFile(file, saveFile);
	// urls[i] = config.getUploadHost(request, type, saveFile
	// .getParentFile().getName(), saveFile.getName());
	// }
	// return new JsonResp<String[]>().data(urls);
	// }

}
